from django.shortcuts import render

# Create your views here.

from rest_framework.views import  APIView
from rest_framework.response import Response
from users.models import UserModel
from django.contrib.auth.hashers import check_password,make_password
from rest_framework_jwt.utils import jwt_encode_handler



class UserView(APIView):
    def post(self,request):
#         1.获取前端传递的数据：
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')

#         判断数据是否齐全：
        if not all([username,password,phone]):
            return Response({'msg':'数据不齐全！','code':404})

#        判断用户是否存在：
        try:
            user=UserModel.objects.get(username=username)
            if user:
                #             判断密码是否正确：
                print(">>>我是第二次")
                # 生成token
                pal = {
                    'user':user.username
                }
                token = jwt_encode_handler(pal)
                if check_password(password, user.password):
                    return Response({'msg': '登录成功', 'code': 200,
                                     'data':{
                                         'user': user.username,
                                         'token': token,
                                     }})
                else:
                    return Response({'msg': '登录失败！', 'code': 404})
        except Exception as e:
            print(e)
            ja_pwd = make_password(password)

            user=UserModel.objects.create(
                username=username,
                password=ja_pwd,
                phone=phone,
            )
            pal = {
                'user': user.username
            }
            token = jwt_encode_handler(pal)
            return Response({'msg':'登录成功','code':200,
                             'data': {
                                 'user': user.username,
                                 'token': token,
                             }})








